// 以流（stream）方式操作文件


const fs  = require('fs');

try {
  fs.writeFileSync('./write.txt', new Array(10*10000).fill('i am a coder').join(','), 'utf8');
  // 设置utf8方式转换为字符串，否则会是Buffer类型
  const readWrite = fs.createReadStream('./write.txt', 'utf8');
  const writeStream = fs.createWriteStream('./writeStream.txt', 'utf8');
  // 读取数据时
  readWrite.on('data', (data) => {
    // 以strean方式写数据
    writeStream.write(data, err => {
      if (err) throw err;
    });
  });
  // 读取数据结束时
  readWrite.on('end', () => {
    console.log('read end');
    // 这里必须在流写完之后调用，否则会报错
    // write流的finish事件会在end方法之后调用
    writeStream.end();
    writeStream.on('finish', () => {
      console.log('该次写完');
    });
  });
} catch (error) {
  throw error;
}
